<template>
  <div class="min-h-screen bg-gray-50 dark:bg-gray-900 py-12">
    <div class="container mx-auto px-4 max-w-7xl">
      <!-- 页面标题 -->
      <div class="mb-12 text-center">
        <h1 class="text-4xl font-bold text-gray-900 dark:text-white mb-4">
          开发者工具评测与资讯
        </h1>
        <p class="text-lg text-gray-600 dark:text-gray-400">
          深度评测、行业趋势、最佳实践，助您做出最佳工具选择
        </p>
      </div>

      <div class="grid grid-cols-1 lg:grid-cols-4 gap-8">
        <!-- 侧边栏 -->
        <aside class="lg:col-span-1">
          <!-- 分类 -->
          <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-6">
            <h3 class="font-semibold text-gray-900 dark:text-white mb-4">分类</h3>
            <div class="space-y-2">
              <button
                @click="selectedCategory = undefined"
                class="block w-full text-left px-3 py-2 rounded-lg transition-colors"
                :class="!selectedCategory ? 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400' : 'hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300'"
              >
                全部分类
              </button>
              <button
                v-for="cat in categories"
                :key="cat.category"
                @click="selectedCategory = cat.category"
                class="block w-full text-left px-3 py-2 rounded-lg transition-colors"
                :class="selectedCategory === cat.category ? 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400' : 'hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300'"
              >
                {{ cat.category }} ({{ cat.count }})
              </button>
            </div>
          </div>

          <!-- 热门标签 -->
          <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6">
            <h3 class="font-semibold text-gray-900 dark:text-white mb-4">热门标签</h3>
            <div class="flex flex-wrap gap-2">
              <button
                v-for="tag in tags"
                :key="tag.tag"
                @click="selectedTag = tag.tag"
                class="px-3 py-1 rounded-full text-sm transition-colors"
                :class="selectedTag === tag.tag ? 'bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400' : 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600'"
              >
                {{ tag.tag }}
              </button>
            </div>
          </div>
        </aside>

        <!-- 文章列表 -->
        <main class="lg:col-span-3">
          <!-- 加载状态 -->
          <div v-if="loading" class="text-center py-12">
            <div class="inline-block animate-spin rounded-full h-12 w-12 border-4 border-blue-600 border-t-transparent"></div>
          </div>

          <!-- 文章列表 -->
          <div v-else-if="articles.length > 0" class="space-y-8">
            <article
              v-for="article in articles"
              :key="article.id"
              class="bg-white dark:bg-gray-800 rounded-lg shadow-sm overflow-hidden hover:shadow-md transition-shadow"
            >
              <NuxtLink :to="`/articles/${article.slug}`" class="block">
                <div class="p-8">
                  <!-- 标签和分类 -->
                  <div class="flex items-center gap-2 mb-3">
                    <span v-if="article.category" class="px-3 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 text-sm rounded-full">
                      {{ article.category }}
                    </span>
                    <span v-if="article.isFeatured" class="px-3 py-1 bg-yellow-100 dark:bg-yellow-900/30 text-yellow-600 dark:text-yellow-400 text-sm rounded-full">
                      精选
                    </span>
                  </div>

                  <!-- 标题 -->
                  <h2 class="text-2xl font-bold text-gray-900 dark:text-white mb-3 hover:text-blue-600 dark:hover:text-blue-400 transition-colors">
                    {{ article.title }}
                  </h2>

                  <!-- 摘要 -->
                  <p class="text-gray-600 dark:text-gray-400 mb-4">
                    {{ article.excerpt }}
                  </p>

                  <!-- 标签 -->
                  <div v-if="article.tags && article.tags.length > 0" class="flex flex-wrap gap-2 mb-4">
                    <span
                      v-for="tag in article.tags.slice(0, 5)"
                      :key="tag"
                      class="text-sm text-gray-500 dark:text-gray-400"
                    >
                      #{{ tag }}
                    </span>
                  </div>

                  <!-- 元信息 -->
                  <div class="flex items-center gap-6 text-sm text-gray-500 dark:text-gray-400">
                    <div class="flex items-center gap-1">
                      <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                      </svg>
                      {{ article.views }}
                    </div>
                    <div class="flex items-center gap-1">
                      <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                      </svg>
                      {{ article.likes }}
                    </div>
                    <div>{{ formatDate(article.publishedAt || article.createdAt) }}</div>
                  </div>
                </div>
              </NuxtLink>
            </article>
          </div>

          <!-- 空状态 -->
          <div v-else class="text-center py-12 bg-white dark:bg-gray-800 rounded-lg">
            <p class="text-gray-600 dark:text-gray-400">暂无文章</p>
          </div>

          <!-- 分页 -->
          <div v-if="totalPages > 1" class="flex justify-center gap-2 mt-8">
            <button
              v-for="page in totalPages"
              :key="page"
              @click="currentPage = page"
              class="px-4 py-2 rounded-lg"
              :class="
                page === currentPage
                  ? 'bg-blue-600 text-white'
                  : 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
              "
            >
              {{ page }}
            </button>
          </div>
        </main>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { useArticles } from '~/composables/useArticles'
import type { Article } from '~/types'

const { getArticles, getCategories, getTags } = useArticles()

const articles = ref<Article[]>([])
const categories = ref<{ category: string; count: number }[]>([])
const tags = ref<{ tag: string; count: number }[]>([])
const loading = ref(false)
const currentPage = ref(1)
const totalPages = ref(0)

const selectedCategory = ref<string | undefined>()
const selectedTag = ref<string | undefined>()

const loadArticles = async () => {
  try {
    loading.value = true
    const response = await getArticles({
      page: currentPage.value,
      limit: 10,
      status: 'published',
      category: selectedCategory.value,
      tag: selectedTag.value,
    })
    articles.value = response.data
    totalPages.value = response.totalPages
  } catch (error) {
    console.error('加载文章失败:', error)
  } finally {
    loading.value = false
  }
}

const loadMetadata = async () => {
  try {
    const [cats, tgs] = await Promise.all([
      getCategories(),
      getTags(),
    ])
    categories.value = cats
    tags.value = tgs.slice(0, 20) // 只显示前20个标签
  } catch (error) {
    console.error('加载分类/标签失败:', error)
  }
}

const formatDate = (dateStr: string): string => {
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' })
}

watch([currentPage, selectedCategory, selectedTag], () => {
  loadArticles()
})

onMounted(() => {
  loadArticles()
  loadMetadata()
})

// SEO优化
const config = useRuntimeConfig()
const siteUrl = config.public.siteUrl || 'http://localhost:3000'

const seoTitle = computed(() => {
  if (selectedCategory.value) {
    return `${selectedCategory.value} - 文章列表 | DevToolsHub`
  }
  return '文章列表 - DevToolsHub | 开发者工具评测与资讯'
})

const seoDescription = computed(() => {
  if (selectedCategory.value) {
    return `浏览 ${selectedCategory.value} 分类下的开发者工具评测文章、行业趋势分析和最佳实践。`
  }
  return '深度评测、行业趋势、最佳实践，助您做出最佳工具选择。阅读开发者工具相关的专业文章和资讯。'
})

useHead({
  title: seoTitle,
  meta: [
    { name: 'description', content: seoDescription },
    { name: 'keywords', content: '开发工具评测,工具对比,开发者资讯,技术文章,工具推荐,最佳实践' },
    
    // Open Graph
    { property: 'og:type', content: 'website' },
    { property: 'og:title', content: seoTitle },
    { property: 'og:description', content: seoDescription },
    { property: 'og:url', content: `${siteUrl}/articles` },
    
    // Twitter Card
    { name: 'twitter:card', content: 'summary' },
    { name: 'twitter:title', content: seoTitle },
    { name: 'twitter:description', content: seoDescription },
  ],
  link: [
    { rel: 'canonical', href: `${siteUrl}/articles` },
  ],
})
</script>

